package cdu.sl.controller;

import cdu.sl.common.PageResult;
import cdu.sl.common.Result;
import cdu.sl.dto.DeptQueryPageParamDTO;
import cdu.sl.entity.Department;
import cdu.sl.entity.Employee;
import cdu.sl.service.DepartmentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/depts")
@RequiredArgsConstructor
@Slf4j
public class DepartmentController {

    private final DepartmentService departmentService;

    /**
     * 查询所有部门
     * @return 部门信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping("/list")
    public Result list(){
        log.info("查询所有部门");
        List<Department> depts=departmentService.queryAll();
        return Result.success(depts);
    }

    /**
     * 新增部门
     */
    @PreAuthorize("hasAuthority('DEPT_ADD')")
    @PostMapping
    public Result add(@RequestBody Department dept){
        log.info("新增部门：{}",dept);
        departmentService.insert(dept);
        return Result.success();
    }

    /**
     * 分页条件查询部门列表
     * @param deptQueryPageParamDTO 分页查询条件
     * @return
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping
    public Result page(DeptQueryPageParamDTO deptQueryPageParamDTO){
        log.info("分页查询部门列表：{}",deptQueryPageParamDTO);
        PageResult<Department> pageResult=departmentService.page(deptQueryPageParamDTO);
        return Result.success(pageResult);
    }


    /**
     * 根据id获取部门信息
     * @param id 部门id
     * @return
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Integer id){
        log.info("根据id获取部门：{}",id);
        Department dept=departmentService.getById(id);
        return Result.success(dept);
    }

    /**
     * 修改部门信息
     * @param dept 部门信息
     * @return
     */
    @PreAuthorize("hasAuthority('DEPT_UPDATE')")
    @PutMapping
    public Result update(@RequestBody Department dept){
        log.info("修改部门信息：{}",dept);
        departmentService.update(dept);
        return Result.success("修改成功");
    }

    /**
     * 根据id删除部门
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('DEPT_DELETE')")
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        log.info("根据id：{}删除部门信息",id);
        departmentService.deleteById(id);
        return Result.success("删除成功");
    }

    /**
     * 根据部门id获取部门下的所有员工
     * @return
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping("/emps/{id}")
    public Result getEmpsByDeptId(@PathVariable("id") Integer id){
        log.info("根据部门id：{}获取部门下所有员工",id);
        List<Employee> empList=departmentService.getEmpsByDeptId(id);
        return Result.success(empList);
    }



}
